package com.nova.scenic.projectlibs.util;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

import com.nova.scenic.projectlibs.util.debug.MyLog;

public abstract class SuccessionEventSimulate {
	private boolean isBegin = false;
	
	private int delay = 200;
	private InternalHandler mHander = null;
	private HandlerThread mThread = null;
	private static final boolean DEBUG = true;
	public SuccessionEventSimulate() {
		
	}
	
	public void prepare() {
		if(mThread == null){
			mThread = new HandlerThread("looper time", android.os.Process.THREAD_PRIORITY_BACKGROUND);
			mThread.start();
		}
		if(mHander == null){
			if(mThread.getLooper() != null){
				mHander = new InternalHandler(mThread.getLooper());
			}

		}
	}
	
	public void setDelay(int delay){
		this.delay = delay;
	}
	
	public void start(){
		start(0);
	}
	
	public void start(int startDlay){
		MyLog.p("SuccessionEventSimulate start startDlay " + startDlay);
		if(!isBegin){
			stop();
			isBegin = true;
			mHander.sendEmptyMessageDelayed(InternalHandler.MSG_START,startDlay);
		}
	}
	
	public void stop(){
		MyLog.p("SuccessionEventSimulate stop" );
		isBegin = false;
		if(mHander != null && mHander.hasMessages(InternalHandler.MSG_START)){
			mHander.removeMessages(InternalHandler.MSG_START);
		}
	}
	
	public void release() {
		stop();
		mHander = null;
		mThread = null;
	}
	
	abstract public void looper();
	
	
	class InternalHandler extends Handler {
		static final int MSG_START = 0;
		public InternalHandler(Looper looper) {
			super(looper);
		}
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case MSG_START:
				if(isBegin){
					looper();
					mHander.sendEmptyMessageDelayed(MSG_START,delay);
				}else{
					stop();
				}
				break;
			}
		};
	}
	
}
